package com.tangji.signaltower.controller;

import com.alibaba.fastjson.JSON;
import com.fqgj.common.api.annotations.ParamsValidate;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.tangji.signaltower.bean.ApiResponse;
import com.tangji.signaltower.controller.request.PushRequest;
import com.tangji.signaltower.enums.BizCodeEnum;
import com.tangji.signaltower.websocket.netty.WebSocketServiceHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * User: Amarendar
 * Date: 2020/07/02
 * Time: 下午6:21
 */
@RestController
@RequestMapping("/message")
public class MessageController {

    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);

    /**
     * list
     *
     * @return
     */
    @RequestMapping(value = "/single/push")
    @ParamsValidate
    public ApiResponse singlePush(@RequestBody PushRequest pushRequest) {
        logger.info("接收到推送请求,{}", JSON.toJSONString(pushRequest));
        if (StringUtils.isEmpty(pushRequest.getDeviceId())
                || StringUtils.isEmpty(pushRequest.getBizCode())
                || StringUtils.isEmpty(pushRequest.getBody())) {
            throw new ApplicationException("Parameter verification failed");
        }
        if (BizCodeEnum.getEnum(pushRequest.getBizCode()) == null) {
            return new ApiResponse<>(500, "The business code does not exist");
        }

        String sessionId = StringUtils.isNotEmpty(pushRequest.getToken()) ? pushRequest.getToken() : pushRequest.getDeviceId();
        pushRequest.setToken(null);
        pushRequest.setDeviceId(null);
        String result = WebSocketServiceHandler.sendMessage(sessionId, JSON.toJSONString(pushRequest));
        logger.info("推送结果,sessionId:{},{}", sessionId, result);
        return new ApiResponse<>();
    }

    /**
     * list
     *
     * @return
     */
    @RequestMapping(value = "/full/push")
    @ParamsValidate
    public ApiResponse fullPush(@RequestBody PushRequest pushRequest) {
        logger.info("接收到全量推送请求,{}", JSON.toJSONString(pushRequest));
        if (StringUtils.isEmpty(pushRequest.getBizCode())
                || StringUtils.isEmpty(pushRequest.getBody())) {
            throw new ApplicationException("Parameter verification failed");
        }
        if (BizCodeEnum.getEnum(pushRequest.getBizCode()) == null) {
            return new ApiResponse<>(500, "The business code does not exist");
        }

        pushRequest.setToken(null);
        pushRequest.setDeviceId(null);

        WebSocketServiceHandler.sendAllMessage(JSON.toJSONString(pushRequest));
        return new ApiResponse<>();
    }

}
